package mju.cxf.aspect;

import mju.cxf.annotation.AutoFill;
import mju.cxf.context.BaseContext;
import mju.cxf.enumeration.OperationType;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.time.LocalDateTime;

/**
 * 公共赋值aop
 */
@Aspect
@Component
public class AddUpdateAspect {
    @Pointcut("execution(* mju.cxf.mapper.*.*(..)) && @annotation(mju.cxf.annotation.AutoFill)")
    public void addUpdateAspect(){}
    @Before("addUpdateAspect()")
    public void autoFill(JoinPoint jp) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        //获取签名对象
       MethodSignature methodSignature =(MethodSignature) jp.getSignature();
        Object[] args = jp.getArgs();
        Object entry=args[0];
        LocalDateTime now = LocalDateTime.now();
        int currentId = BaseContext.getCurrentId();
        //获取注解
        AutoFill af=methodSignature.getMethod().getAnnotation(AutoFill.class);
        if (af.value().equals(OperationType.UPDATE) ){
            Method setUpdateTime = entry.getClass().getDeclaredMethod("setUpdateTime", LocalDateTime.class);
//            Method setUpdateUser = entry.getClass().getDeclaredMethod("setUpdateUser", Long.class);
//            setUpdateUser.invoke(entry,currentId);
            setUpdateTime.invoke(entry,now);
        }else{
//            Method setCreateUser = entry.getClass().getDeclaredMethod("setCreateUser", Long.class);
            Method setCreateTime = entry.getClass().getDeclaredMethod("setCreateTime", LocalDateTime.class);
//            setCreateUser.invoke(entry,currentId);
            setCreateTime.invoke(entry,now);
        }
    }
}
